<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="lawyer_name" label="律师名称" required>
				<uni-easyinput placeholder="律师的全名" v-model="formData.lawyer_name"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="license_number" label="执业证号" required>
				<uni-easyinput placeholder="律师的执业证号" v-model="formData.license_number"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="email" label="邮箱" required>
				<uni-easyinput placeholder="律师的邮箱地址" v-model="formData.email"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="law_firm" label="执业律所" required>
				<uni-easyinput placeholder="律师所在的律所名称" v-model="formData.law_firm"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="contact_phone" label="联系电话" required>
				<uni-easyinput placeholder="律师的联系电话" v-model="formData.contact_phone"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="contact_address" label="联系地址">
				<uni-easyinput placeholder="律师的联系地址" v-model="formData.contact_address"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="legal_specialty" label="法律专长">
				<uni-data-checkbox :localdata="legalSpecialtyOptions" :multiple="true"
					v-model="formData.legal_specialty"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item name="practice_slogan" label="执业感言">
				<uni-easyinput placeholder="律师的执业感言" v-model="formData.practice_slogan"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="douyin_account" label="抖音号">
				<uni-easyinput placeholder="律师的抖音账号" v-model="formData.douyin_account"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="lawyer_intro" label="律师简介">
				<uni-easyinput placeholder="律师的简要介绍" v-model="formData.lawyer_intro"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="practice_region" label="执业地区">
				<uni-section title="律师的执业地区" type="line" padding style="height: calc(100vh - 100px);">
					<uni-data-picker placeholder="请选择地区" popup-title="请选择所在地区" :localdata="dataTree"
						v-model="formData.practice_region" @change="onchange" @nodeclick="onnodeclick">
					</uni-data-picker>
				</uni-section>
			</uni-forms-item>
			<uni-forms-item name="personal_photo" label="个人照片">
				<uni-file-picker file-mediatype="image" return-type="object"
					v-model="formData.personal_photo"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="license_photo" label="执业证照片">
				<uni-file-picker file-mediatype="image" return-type="object"
					v-model="formData.license_photo"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="showcase_photos" label="风采照片">
				<uni-file-picker file-mediatype="image" return-type="object"
					v-model="formData.showcase_photos"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="is_featured" label="是否推荐页显示">
				<switch @change="binddata('is_featured', $event.detail.value)" :checked="formData.is_featured"></switch>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/lawyers.js';
	import area from '../area/provinces.json'
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'lawyers';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"lawyer_name": "",
				"license_number": "",
				"email": "",
				"law_firm": "",
				"contact_phone": "",
				"contact_address": "",
				"legal_specialty": [],
				"practice_slogan": "",
				"douyin_account": "",
				"lawyer_intro": "",
				"practice_region": "",
				"personal_photo": null,
				"license_photo": null,
				"showcase_photos": null,
				"is_featured": null
			}
			return {
				formData,
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				},
				legalSpecialtyOptions: [],
				dataTree: area
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		created() {
			// 在页面加载时动态获取数据
			this.fetchLegalSpecialtyOptions();
		},
		methods: {
			onchange(e) {
				const value = e.detail.value
				console.log(e)
			},
			onnodeclick(node) {
				console.log(node)
			},
			/**
			 * 获取分类
			 */
			async fetchLegalSpecialtyOptions() {
				try {
					const db = uniCloud.database();
					const res = await db.collection('legal-categories').get();
					// 将查询结果映射为 localdata 格式
					this.legalSpecialtyOptions = res.result.data.map(item => ({
						value: item._id, // 数据库中保存的唯一标识符
						text: item.name // 数据库中的显示名称
					}));

				} catch (err) {
					console.error('Error fetching legal specialties:', err);
				}
			},

			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).add(value).then((res) => {
					uni.showToast({
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			}
		}
	}
</script>